#include <iostream>
#include <dirent.h> // 文件系统相关库
#include "LinkTree.h"
#include <sys/stat.h>


std::string Double2(double num)
{
    return std::to_string((1.0*(int)(num*100)/100));
}

std::string Transform(size_t size)
{
    if(size < 1024)
        return Double2(size) + "B";
    else if(size < 1024*1024)
        return Double2(1.0 * size / 1024) + "KB";
    else if(size < 1024*1024*1024)
        return Double2(1.0 * size / (1024*1024)) + "MB";
    else 
        return Double2(1.0 * size / (1024*1024*1024)) + "GB";
}

// 扫描文件夹
void ExploreDirectory(const std::string &path,TreeNode* node)
{
    // 打开文件流
    DIR *dir = opendir((path+"/").c_str());
    if (dir == nullptr)
    {
        std::cout << "文件夹路径有误!" << path << std::endl;
        return;
    }
    // 读取文件目前下的列表
    dirent *e = nullptr;
    while ((e = readdir(dir)) != nullptr)
    {
        if(std::string(e->d_name) == "." || std::string(e->d_name) == "..")
            continue;
        TreeNode* child = new TreeNode(e->d_name);
        child->Connect(node);
        if(e->d_type == DT_DIR)
        {
            ExploreDirectory(path+"/"+std::string(e->d_name),child);
        }
        else
        {
            struct stat s;
            stat((path+"/"+std::string(e->d_name)).c_str(),&s);
            child->SetData(std::string(e->d_name) + "         size:"  + Transform(s.st_size));
        }
    }
    //关闭目录流
    closedir(dir);
}

void Find(LinkTree& tree,const std::string &name)
{

    DARRAY::DynamicArray a = tree.FindByElement(name);
    
    for(int i = 0;i<a.Size();i++)
    {
        std::cout<<tree.GetNodePath((TreeNode*)a[i])<<std::endl;
    }
}

//argc : 代表命令行参数数量
//argv : 代表命令行参数值数组

int main(int argc,char* argv[])
{
    // std::cout << argc <<std::endl;

    // for(int i = 0;i<argc;i++)
    // {
    //     std::cout<<argv[i]<<std::endl;
    // }

    std::string path;
    if(argc < 2)
    {
        path = ".";
    }
    else
    {
        path = argv[1];
    }
    LinkTree tree(path);
    ExploreDirectory(path,tree.GetRoot());
    tree.show();

    


    

    // if(argc >= 3)
    // {
    //     Find(tree,argv[2]);
    // }
    // else
    // {
    //     std::cout<<"未输入查找文件名!\n";
    // }
    

    return 0;
}